package com.fsnbigdata.web;

import com.fsnbigdata.domain.Log;
import com.fsnbigdata.service.api.LogService;
import com.fsnbigdata.util.DateUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping( value = "/api/Excel", produces = MediaType.APPLICATION_JSON_VALUE )
@Api(tags = "Excel", description = "Excel导出" )
public class ExcelController {

    @Autowired
    private LogService logService;

    //生成log表excel
    @RequestMapping("/exportExcel")
    @PreAuthorize("hasRole('ROLE_USER_ADMIN')")
    public String getUser(HttpServletResponse response,HttpServletRequest request) throws Exception{
        String status = request.getParameter("status");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String type = request.getParameter("genre");
        String key = request.getParameter("description");
        List<Log> rows = new ArrayList<>();
        if(status==null||"".equals(status)||"0".equals(status)){
            rows= logService.findAllByTime(startTime,endTime,type,key);
        }else {
            Date date = DateUtil.getEndOfDay(new Date());
            Calendar c = Calendar.getInstance();
            status = (status==null?"":status);
            switch (status){
                //近一周
                case "1":
                    c.setTime(date);
                    c.add(Calendar.DATE, - 7);
                    startTime = c.getTime().getTime()/1000+"";
                    endTime = date.getTime()/1000+"";
                    break;
                //近一月
                case "2":
                    c.setTime(date);
                    c.add(Calendar.MONTH, - 1);
                    startTime = c.getTime().getTime()/1000+"";
                    endTime = date.getTime()/1000+"";
                    break;
                //近三月
                case "3":
                    c.setTime(date);
                    c.add(Calendar.MONTH, - 3);
                    startTime = c.getTime().getTime()/1000+"";
                    endTime = date.getTime()/1000+"";
                    break;
                //近半年
                case "4":
                    c.setTime(date);
                    c.add(Calendar.MONTH, - 6);
                    startTime = c.getTime().getTime()/1000+"";
                    endTime = date.getTime()/1000+"";
                    break;
                //近一年
                case "5":
                    c.setTime(date);
                    c.add(Calendar.YEAR, - 1);
                    startTime = c.getTime().getTime()/1000+"";
                    endTime = date.getTime()/1000+"";
                    break;
            }
            rows = logService.findAllByTime(startTime,endTime,type,key);
        }


        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("log");
        createTitle(workbook,sheet);
        //设置日期格式
        HSSFCellStyle style = workbook.createCellStyle();
        style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

        //新增数据行，并且设置单元格数据
        int rowNum=1;
        if(rows.size()>0){
            for(Log log:rows){
                HSSFRow row = sheet.createRow(rowNum);
                String genre = "数据出错";
                if("0".equals(log.getGenre())){
                    genre = "正常请求";
                }
                if("1".equals(log.getGenre())){
                    genre = "异常请求";
                }
                if("2".equals(log.getGenre())){
                    genre = "报警";
                }
                row.createCell(0).setCellValue(log.getId());
                row.createCell(1).setCellValue(log.getType());
                row.createCell(2).setCellValue(log.getUsername());
                row.createCell(3).setCellValue(log.getDescription());
                row.createCell(4).setCellValue(log.getAddress());
                row.createCell(5).setCellValue(log.getClientInformation());
                row.createCell(6).setCellValue(genre);
                row.createCell(7).setCellValue(log.getIp());
                HSSFCell cell = row.createCell(8);
                cell.setCellValue(log.getCreateTime());
                cell.setCellStyle(style);
                rowNum++;
            }
        }
        String fileName = "log.xls";

        //生成excel文件
        buildExcelFile(fileName, workbook);

        //浏览器下载excel
        buildExcelDocument(fileName,workbook,response);

        return "download log.xls";
    }

    private void createTitle(HSSFWorkbook workbook,HSSFSheet sheet){
        HSSFRow row = sheet.createRow(0);
        //设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
        sheet.setColumnWidth(1,12*256);
        sheet.setColumnWidth(3,17*256);

        //设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBold(true);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setFont(font);

        HSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);


        cell = row.createCell(1);
        cell.setCellValue("类型");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("用户名");
        cell.setCellStyle(style);

        cell = row.createCell(3);
        cell.setCellValue("描述");
        cell.setCellStyle(style);

        cell = row.createCell(4);
        cell.setCellValue("地址");
        cell.setCellStyle(style);

        cell = row.createCell(5);
        cell.setCellValue("客户端主机名");
        cell.setCellStyle(style);

        cell = row.createCell(6);
        cell.setCellValue("日志类型");
        cell.setCellStyle(style);

        cell = row.createCell(7);
        cell.setCellValue("访问ip");
        cell.setCellStyle(style);

        cell = row.createCell(8);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);

    }
    //生成excel文件
    protected void buildExcelFile(String filename,HSSFWorkbook workbook) throws Exception{
        String path = new File("").getCanonicalPath();
        path = path+"\\Excel";

        File file =new File(path);
        //如果文件夹不存在则创建
        if  (!file .exists()  && !file .isDirectory())
        {
            file.mkdir();
        }

        String url = path+"/"+filename;
        FileOutputStream fos = new FileOutputStream(url);
        workbook.write(fos);
        fos.flush();
        fos.close();
    }

    //浏览器下载excel
    protected void buildExcelDocument(String filename,HSSFWorkbook workbook,HttpServletResponse response) throws Exception{
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename, "utf-8"));
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
